/*
 * Copyright (c) 2011, Will Strohl
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list 
 * of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright notice, this 
 * list of conditions and the following disclaimer in the documentation and/or 
 * other materials provided with the distribution.
 * 
 * Neither the name of WillStrohl.com nor the names of its contributors may be used 
 * to endorse or promote products derived from this software without specific prior 
 * written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE 
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI.WebControls;
using DotNetNuke.Common;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.UI.Skins.Controls;

namespace DotNetNuke.Modules.WillStrohlDisqus
{

    /// -----------------------------------------------------------------------------
    /// <summary>
    /// The EditWillStrohlDisqus class is used to manage content
    /// </summary>
    /// -----------------------------------------------------------------------------
    public partial class Edit : WillStrohlDisqusModuleBase
    {

        #region Private Properties

        private int AttachedModule { get; set; }
        private string ApplicationName { get; set; }

        #endregion

        #region Event Handlers

        /// <summary>
        /// OnInit - initialization of the module
        /// </summary>
        /// <param name="e"></param>
        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            this.Load += new System.EventHandler(this.PageLoad);
            this.cmdSave.Click += new System.EventHandler(this.CmdSaveClick);
            this.cmdReturn.Click += new System.EventHandler(this.CmdReturnClick);
        }

        /// -----------------------------------------------------------------------------
        /// <summary>
        /// Page_Load runs when the control is loaded
        /// </summary>
        /// -----------------------------------------------------------------------------
        private void PageLoad(object sender, System.EventArgs e)
        {
            try
            {
                if(!this.IsPostBack)
                {
                    this.BindData();
                }
            }
            catch (Exception exc) //Module failed to load
            {
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }

        private void CmdSaveClick(object sender, System.EventArgs e)
        {
            if (this.Page.IsValid)
            {
                this.SaveSettings();
                this.SendBackToModule();
            }
        }

        private void CmdReturnClick(object sender, System.EventArgs e)
        {
            this.SendBackToModule();
        }

        #endregion

        #region Private Helper Methods

        private void BindData()
        {
            this.LocalizeModule();

            Dictionary<int, ModuleInfo>.ValueCollection collModule = new ModuleController().GetTabModules(this.TabId).Values;

            foreach (ModuleInfo objModule in collModule)
            {
                if (objModule.ModuleID == this.ModuleId) continue;

                if (!string.IsNullOrEmpty(objModule.ModuleTitle.Trim()))
                {
                    this.cboModuleList.Items.Add(new ListItem(objModule.ModuleTitle, objModule.ModuleID.ToString()));
                }
                else
                {
                    this.cboModuleList.Items.Add(new ListItem(this.GetLocalizedString("NoName.Text"), objModule.ModuleID.ToString()));
                }
            }
            this.cboModuleList.Items.Insert(0, new ListItem("---"));

            if (this.Settings["AttachedModuleId"] != null)
                this.AttachedModule = int.Parse(this.Settings["AttachedModuleId"].ToString(), NumberStyles.Integer);

            if (this.Settings["ApplicationName"] != null)
                this.ApplicationName = this.Settings["ApplicationName"].ToString();

            try
            {
                if (this.AttachedModule > 0)
                    this.cboModuleList.Items.FindByValue(this.AttachedModule.ToString()).Selected = true;
            }
            catch
            {
                ModuleController ctlModule = new ModuleController();
                ctlModule.DeleteModuleSetting(this.ModuleId, "AttachedModuleId");
                ModuleController.SynchronizeModule(this.ModuleId);
                this.cboModuleList.SelectedIndex = 0;
            }

            this.txtAppName.Text = this.ApplicationName;
        }

        private void LocalizeModule()
        {
            this.rfvModuleList.ErrorMessage = this.GetLocalizedString("rfvModuleList.ErrorMessage");
            this.rfvAppName.ErrorMessage = this.GetLocalizedString("rfvAppName.ErrorMessage");
            this.cmdSave.Text = this.GetLocalizedString("cmdSave.Text");
            this.cmdReturn.Text = this.GetLocalizedString("cmdReturn.Text");
        }

        private void SaveSettings()
        {
            ModuleController ctlModule = new ModuleController();
            ctlModule.UpdateModuleSetting(this.ModuleId, "ApplicationName", this.txtAppName.Text);
            ctlModule.UpdateModuleSetting(this.ModuleId, "AttachedModuleId", this.cboModuleList.SelectedValue);
            ModuleController.SynchronizeModule(this.ModuleId);
        }

        private void SendBackToModule()
        {
            Response.Redirect(Globals.NavigateURL());
        }

        #endregion

    }

}